package ;

import haxe.PosInfos;
import php.db.Connection;
import php.db.ResultSet;
import php.io.File;
import php.Lib;
import php.Session;
import php.Web;
import UserType;

/**
 * ...
 * @author Axel Huizinga axel@cunity.me
 */

class Main 
{

	public static var param:Hash<String>;
	static var cnx:Connection = connect();
	public static var userType:UserType;
	static var auth:Auth;
	static var initScript:String = '';
	
	static function main() 
	{
		if (cnx == null)
		{
			Lib.print("<div>Die Datenbank meldet folgenden Fehler:\n" + untyped __php__("mysql_error()") + "</div>");
			return;
		}
		
		param = Web.getParams();
		var path:String = param.get('path');
		Session.start();
		switch(path)
		{
			case 'admin':
			//Session.set('PATH_PREV', Session.exists('PATH') ? Session.get('PATH') : 'home');
			switch(param.get('task'))
			{
				case 'editCat':				
				Session.set('PATH', 'katzen');
				
				case 'editLink':
				Session.set('PATH', 'links');
			}
			
			case 'dologin', 'dologout':
			//RESET 2 LAST_PATH
			errLog('PATH_PREV:' + Session.get('PATH_PREV') + ' PATH:' + Session.get('PATH') );
			if (!Session.exists('PATH_PREV'))
			Session.set('PATH_PREV', Session.exists('PATH') ? Session.get('PATH') : 'home');	
			Session.set('PATH',  Session.get('PATH_PREV'));
			
			case 'logout':
			Session.set('PATH_PREV', Session.exists('PATH') ? Session.get('PATH') : 'home');

			default:
			errLog(path == null ? 'null' : 'notnull') ;
			Session.set('PATH_PREV', Session.exists('PATH') ? Session.get('PATH') : 'home');	
			if (path == '' ) path = Session.get('PATH_PREV');
			Session.set('PATH',  path);
			param.set('path', path);
			errLog('set session path 2:' + path);
		}
		//Session.close();
		//Session.start();
		
		errLog('path = null:' + (path == null ? 'true': 'false') + ':' +path);
		if (path == '' || path == null)
		{
			//initScript  = '<script type="text/javascript">frames["menuFrame"].location.href="menu.php?init=1";</script>';
			//initScript  = '<script type="text/javascript">debug(frames.length);for(f=0;f<frames.length;f++)debug(frames[f].name);debug(parent.frames.length);</script>';
			path = Session.get('PATH');
		}
		/*for (k in param.keys())
		if(k!='open')
		errLog(k + ':' + param.get(k));*/
		errLog('uri:' + Web.getURI());
		errLog('path:' + param.get('path') + ' task:' + param.get('task') + ' PATH:' + Session.get('PATH')+ ' PATH_PREV:' +Session.get('PATH_PREV'));
		run();
	}
	
	public static function run()
	{
		switch(param.get('path'))
		{
			case 'checkAuth':
			auth = new Auth(cnx);
			auth.checkAuth();
			output(auth.res.toString());	
				
			case 'links':
			auth = new Auth(cnx);
			auth.checkAuth();
			output(Link.displayAll(userType));
			
			case 'dologin', 'dologout':
			auth = new Auth(cnx);
			var out:String = '';
			if (param.get('path') == 'dologin' && !auth.login())
			{
				errLog('Auth.res:' + auth.res.toString());
				output(auth.res.toString(), false);	
				return;
			}
			else			
			{
				initScript =  '<script type="text/javascript">parent.updateLoginState(' 
					+ (param.get('path') == 'dologin' ? '"login",' : '"logout", "' ) + Session.get('PATH_PREV') + '");</script>';
				var prevPath:String = (Session.exists('PATH_PREV') ? Session.get('PATH_PREV') : 'home');
				errLog('PATH_PREV:' + prevPath + ':' + (param.get('path') == 'dologin' ? '"login-",' : '"logout-", "'));
				switch(prevPath)
				{
					case 'katzen':
					out = Cats.displayAll(userType);
					
					case 'links':
					out = Link.displayAll(userType);
					
					default:
					out = File.getContent("http://"+ Web.getHostName() + '/source.php?path=' + Session.get('PATH_PREV'));
					
				}				
				if(~/(<script[^>]*>)/.match(out))
					out = ~/(<script[^>]*>)/.replace(out, initScript + "$1");
				errLog('initScript inserted:' + Std.string(~/(<script[^>]*>)/.match(out)) +':' + initScript.length + ':' +out.length);
				output(out, false);
			}
			
			case 'logout': 
			auth = new Auth(cnx);
			if(!auth.logout())
				output(auth.res.toString());
			else
				return;
			case 'admin':
			auth = new Auth(cnx);
			auth.admin();
			//output(auth.res.toString());
			//Web.setHeader('Location', 'http://' + php.Sys.getEnv('SERVER_NAME')+ '/admin.php');
			//param.set('do', 'cats');
			//output(Cats.displayAll(UserType.admin));
			case 'cat':			
			if(param.exists('id'))
			{
				var cat:Cats = Cats.manager.get(Std.parseInt(param.get('id')));
				if (cat != null)
				{
					output(cat.displayAllImages(),false);
				}
				else
					Main.errLog('cat:' + param.get('id') + ' not found!');
			}

			default:
			auth = new Auth(cnx);
			auth.checkAuth();			
			output(Cats.displayAll(userType));
			//output(param.toString());
		}
		cleanup();
	}
	
	static function connect():Connection
	{
		var cx:Connection = null;
		try 
		{
			cx = php.db.Mysql.connect({ 
					host : "localhost",
					port : 3306,
					database : "samtpfoten",
					user : "samtpfoten",
					pass : "katzenfee",
					socket : null
				});
			php.db.Manager.cnx = cx;
			php.db.Manager.initialize();			
		}
		catch (ex:Dynamic) { return cx; }
		
		return cx;
	}
	
	
	static function cleanup()
	{		
		php.db.Manager.cleanup();
		cnx.close();
	}
	
	public static function output(what:String, xmlCType:Bool = false)
	{
		if(xmlCType)
			Web.setHeader('Content-type', 'text/xml');
		else
		{
			//what = ~/<\?.*\?>/.replace(what, '');header("Content-Type: text/html; charset=utf-8");
			Web.setHeader('Content-type', 'text/html; charset=utf-8');
		}
		//errLog(what);
		Lib.print(what);
	}
	
	public static function errLog(m:Dynamic, ?i:PosInfos)
	{
		var ms:String = Std.is(m, String) ? m : Std.string(m);
		var msg = if ( i != null ) i.fileName + ':' + i.lineNumber + ": " + i.methodName  else "";
		if (false && ms.length > 100)
		untyped __call__("error_log",  
			"<textarea cols='80' rows='15'>"+ msg +':' + untyped __call__('htmlspecialchars', ms) + "</textarea>");
		else
		untyped __call__("error_log",   msg +':' + untyped __call__('htmlspecialchars', ms.substr(0,50)));
	}

}